/**
 * Created by Eoly on 2017/2/16.
 * Call http://palerock.cn
 */

// 获取状态栏高度
var immersed = 0;
// var immersed = 20;
var ms = (/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);
if (ms && ms.length >= 3) { // 当前环境为沉浸式状态栏模式
    immersed = parseFloat(ms[2]);// 获取状态栏的高度
}


var net = "http://palerock.cn/h5_back";

var app = {};

// 实现沉浸状态栏效果
app.adapt = function (isNotChangeContent) {

    var $content = $('.content');

    var normalHeight = 2.2;
    var t = document.getElementsByClassName('to-padding-top');
    for (var i = 0; i < t.length; i++) {
        t[i].style.paddingTop = immersed + 'px';
        t[i].style.boxSizing = 'content-box';
        if ($(t[i]).hasClass('bg')) {
            t[i].style.height = 150 + 'px';
            t[i].style.paddingTop = 0;
            t[i].style.height = t[i].offsetHeight + immersed + 'px';
        }
        if($(t[i]).hasClass('search-box')){
            var content = document.getElementsByClassName('content')[0];
            content.style.top = 3 + 'rem';
            console.log(content.offsetTop);
            content.style.top = content.offsetTop + immersed + 'px';
        }
    }
    if (!isNotChangeContent) {
        var g = document.getElementsByClassName('content')[0];
        g.style.top = normalHeight + 'rem';
        g.style.top = g.offsetTop + immersed + 'px';
        if ($content.hasClass('pull-to-refresh-content')) {
            g.style.top = immersed + 'px';
        }
    }
};

app.suiInit = function (isNotChangeContent) {
    // 默认的init 方法
    var $page = $(".page-current");
    if (!$page[0]) $page = $(".page").addClass('page-current');
    var id = $page[0].id;
    if (!$page[0]) $page = $(document.body);
    var $content = $page.hasClass('content') ?
        $page :
        $page.find('.content');
    $content.scroller();  //注意滚动条一定要最先初始化

    $.initPullToRefresh($content);
    $.initInfiniteScroll($content);
    $.initCalendar($content);

    //extend
    // if ($.initSwiper) $.initSwiper($content);

    $page.trigger('pageInit', [id, $page]);

    // 实现沉浸状态栏效果
    app.adapt(isNotChangeContent);
};

// 储存当前位置
app.savePosition = function (url, sharp) {
    if (!url || !sharp) {
        return;
    }
    var record = {};
    record.url = url;
    record.sharp = sharp;
    var recordList = sessionStorage.getItem('ptsc_position_record');
    if (!recordList || recordList == '[]') {
        recordList = [];
        recordList.push(record);
        sessionStorage.setItem('ptsc_position_record', JSON.stringify(recordList));
        return;
    }
    recordList = JSON.parse(recordList);
    for (var i = 0; i < recordList.length; i++) {
        if (record.url == recordList[i].url) {
            if (record.sharp == recordList[i].sharp) {
                return;
            } else {
                recordList.splice(i, 1);
                break;
            }
        }
    }
    recordList.push(record);
    sessionStorage.setItem('ptsc_position_record', JSON.stringify(recordList));
};

// 返回到上一个位置
app.backLastPosition = function () {
    var record = {};
    var recordList = sessionStorage.getItem('ptsc_position_record');
    if (!recordList || recordList == '[]') {
        return false;
    }
    recordList = JSON.parse(recordList);
    record = recordList.pop();
    sessionStorage.setItem('ptsc_position_record', JSON.stringify(recordList));
    location.href = record.url + record.sharp;
};

// 设定跳转链接的动作
app.turnHref = function (url, sharp, aim_url,needLogin) {
    if(!needLogin) {
        app.savePosition(url, sharp);
        location.href = aim_url;
    }else {
        if(!app.getUserToken()){
            $.toast('您需要登录才能进行此操作',800,'toastToBot');
            return;
        }
        app.savePosition(url, sharp);
        location.href = aim_url;
    }
};

app.test = function (is) {
    if (is)
        console.log(9999);
    else
        console.log(8888);

};

// 适应手机输入
app.adaptPhone = function () {
    $('input,textarea').focus(function () {
        var a = $('.content');
        var _this = this;
        setTimeout(function () {
            if (!a) {
                return;
            }
            a.scrollTop($(_this).offset().top - a.offset().top);
        }, 500);
    });
};

app.mergeTest = function () {
    var oj = Object.assign({a: 1}, {b: 5});
    console.log(oj)
};

function plusReady() {
    var isPreToExitOne = false;
    var isPreToExitTwo = false;
    plus.key.addEventListener("backbutton", function () {
        if (isPreToExitTwo) {
            plus.runtime.quit();
        }
        if (!isPreToExitOne) {
            app.backLastPosition();
            isPreToExitOne = true;
            window.setTimeout(function () {
                isPreToExitOne = false;
            }, 500)
        } else {
            isPreToExitTwo = true;
            window.setTimeout(function () {
                isPreToExitTwo = false;
            }, 1500);
            $.toast('再次按返回键退出', 1500, 'toastToBot');
        }
    }, false);
}

if (window.plus) {
    plusReady();
} else {
    document.addEventListener("plusready", plusReady, true);
}

app.getUserToken = function () {
    var token = localStorage.getItem('ptsc_user_token');
    if (!token) {
        if(!sessionStorage.getItem('ptsc_none_login')){
            $.modal({
                title: '您还没有登录',
                text: '注册登录后可以参团抢购你喜欢的商品，还可以发团去售卖你自己的商品',
                buttons: [
                    {
                        text: '去登录',
                        onClick: function () {
                            app.turnHref('index.html', '#mine', 'user-check.html#login');
                        }
                    },
                    {
                        text: '去注册',
                        onClick: function () {
                            app.turnHref('index.html', '#mine', 'user-check.html#register');
                        }
                    },
                    {
                        text: '下次再说',
                        onClick: function () {
                        }
                    }
                ]
            });
            sessionStorage.setItem('ptsc_none_login','ture');
        }else {
            // $.toast('您还没有登录',800,'toastToBot');
        }
    }
    return token;
};

//自定义过滤器——转换团状态为文字
app.beToGroupStatus = function (status) {
    var result = '';
    switch (status) {
        case -1:
            result = '审核中';
            break;
        case 0:
            result = '拼团中';
            break;
        case 1:
            result = '拼团成功';
            break;
        case 2:
            result = '拼团失败';
            break;
        default:
            result = '未知状态';
    }
    //input 就是我们要处理的数据
    return result;
};

//自定义过滤器——追加文字
app.appendText = function (value, text) {
    if (!value) {
        return null;
    }
    return value + text;
};

//自定义过滤器——解释权限
app.explainPower = function (power) {
  switch (power){
      case 0:
          return '<span class="user-power zero">普通成员</span>';
      case 1:
          return '<span class="user-power first">大众会员</span>';
      case 2:
          return '<span class="user-power second">VIP</span>';
      case 3:
          return '<span class="user-power admin">管理员</span>';
      default:
          return '';
  }
};

//自定义过滤器——还有多少时间过期
app.explainTime = function (time) {

    if(time<=0){
        return '该团已失效'
    }

    var date = parseInt(time/86400000);
    var hours = parseInt(time%86400000/3600000);
    var min = parseInt(time%86400000%3600000/60000);
    var seconds = parseInt(time%86400000%3600000%60000/1000);

    // console.log(date+'天'+hours+'时'+min+'分'+seconds+'秒');

    return date+'天'+hours+'时'+min+'分'+seconds+'秒';

};

app.openAndScanPsw = function (text, callback) {
    $.modal({
        text: text,
        afterText: '<div class="list-block" style="margin: 1rem 0;border: 1px solid white"><input type="password" name="" id="psw-model"></div>',
        buttons: [
            {
                text: '取消',
                onClick: function () {
                    callback(null);
                }
            },
            {
                text: '确认',
                bold: true,
                onClick: function () {
                    var a = document.getElementById('psw-model');
                    if (a.value == null) {
                        a.value = '';
                    }
                    callback(a.value);
                }
            }
        ]
    });
};

app.modalTest = function () {
    app.openAndScanPsw('请输入密码', function (value) {
        console.log(value);
        $.alert('你输入的密码是' + value);
    })
};

app.filterOptionsAction = function (title, options, locked_index, cb) {

    if (!options.length) {
        return;
    }

    var content = [];

    content.push(
        ' <div class="list-block action-list "><ul>'
    );

    console.log(options);

    for (var i = 0; i < options.length; i++) {
        if (options[i].value == locked_index) {
            content.push(
                '<li><label class="label-checkbox item-content">\
                     <input type="radio" name="option" value="' + options[i].value + '" checked>\
                     <div class="item-media"><i class="icon icon-form-checkbox"></i></div>\
                      <div class="item-inner">\
                         <div class="item-title-row">\
                             <div class="item-title">' + options[i].name + '</div>\
                         </div>\
                       </div>\
                </li></label>'
            );
            continue;
        }
        content.push(
            '<li><label class="label-checkbox item-content">\
                 <input type="radio" name="option" value="' + options[i].value + '">\
                 <div class="item-media"><i class="icon icon-form-checkbox"></i></div>\
                  <div class="item-inner">\
                     <div class="item-title-row">\
                         <div class="item-title">' + options[i].name + '</div>\
                     </div>\
                   </div>\
            </label></li>'
        )
    }

    content.push(
        '</ul></div>'
    );

    var htmlText = content.join('');


    var buttons1 = [
        {
            text: title,
            label: true
        },
        {
            text: htmlText,
            label: true
        }
    ];
    var buttons2 = [
        {
            text: '确定',
            bg: 'danger'
        }
    ];
    var groups = [buttons1, buttons2];
    $.actions(groups);

    var ele = $('.action-list label');
    ele.click(function () {
        var value = $(this).find('input').val();
        cb(value);
    })

};

app.actionTest = function () {
    var options = [
        {
            name: '审核中',
            value: -1
        },
        {
            name: '拼团中',
            value: 0
        },
        {
            name: '拼团成功',
            value: 1
        },
        {
            name: '拼团失败',
            value: 2
        }
    ];
    app.filterOptionsAction('选择状态', options, 1, function (e) {
        alert('你选择的状态是：' + e);
    });
};


// base64 算法功能
app.Base64 = function () {

    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    };

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    };

    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    };

    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};


//获取登录用户
app.getLoginUser = function () {

    //获取登录信息
    var token = app.getUserToken();

    if (!token) {
        return;
    }

    var infoBits = token.split('.');

    // console.log(infoBits);

    var base = new app.Base64();

    var user_string = base.decode(infoBits[1]);

    console.log(user_string);

    var result =JSON.parse(user_string);

    return JSON.parse(result.sub);

};